go to previous page   go to home page   go to next page

Could print() use the reference to the original String object to change the contents of that object?

Answer:

No — because String objects are immutable. Not even the main() method can change the original object.


Mutable and Immutable Objects

It is good that String objects are immutable (they can't be changed) because the main() method can be sure that the message is completely under its control. Although the print() method gets a copy of the reference, it can't change the original object.

Not all objects are immutable. For example, in the following, MyPoint objects have public instance variables x and y. These can be changed by any method that has a reference to the object.

Important: Public instance variables of objects can be changed by any method that has a reference to the object.

(If an instance variable is neither public nor private it can be changed by a method that is in the same package. For now, all of our code is in the same package, so the effect is the same as if it were public. To keep all of your code in the same package, put all the files needed for a program in the same subdirectory. )

The main() method uses the default constructor of class MyPoint. This is the constructor you get automatically if you do not define one yourself.


class MyPoint
{
  public int x=3, y=5;

  public void print()
  {
    System.out.println("x = " + x + "; y = " + y );
  }
}

class PointTester
{
  public static void main ( String[] args )
  {
    MyPoint pt = new MyPoint();

    pt.print();

    pt.x = 45;  pt.y = 83;

    pt.print();
  }
}

QUESTION 10:

What is the output of the program?

x = ; y =

x = ; y =